package com.easylinkin.linkappapi.security.config;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class RequestFilter implements Filter {

  @Value("${system.request.time}")
  private Long requestTime;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    Filter.super.init(filterConfig);

  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
      if (System.currentTimeMillis()<=requestTime || httpServletRequest.getServletPath().contains("checkhealth")){
        filterChain.doFilter(servletRequest, servletResponse);
      }else{
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpResponse.getWriter().write("Request is forbidden.");
        return; // 中断请求处理流程
      }
  }

  @Override
  public void destroy() {
    Filter.super.destroy();
  }

  public Long getRequestTime() {
    return requestTime;
  }
}
